<template>
  <div class="resources-container">
    <el-tabs v-model="activeTab" @tab-click="handleTabChange" class="record-tabs">
      <el-tab-pane label="资源总表" name="0"></el-tab-pane>
<!--      <el-tab-pane label="部门资源" name="1"></el-tab-pane>-->
<!--      <el-tab-pane label="资源统计" name="2"></el-tab-pane>-->
    </el-tabs>

    <el-card class="filter-card">
      <el-form :inline="true" :model="queryParams" class="filter-form">
        <!-- 资源总表和部门资源的搜索框 -->
        <template v-if="activeTab !== '2'">
          <el-form-item label="资源名称" prop="resourceName">
            <el-input
              v-model="queryParams.resourceName"
              placeholder="请输入资源名称"
              clearable
              style="width: 180px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="区域" prop="region">
            <el-input
              v-model="queryParams.region"
              placeholder="请输入区域"
              clearable
              style="width: 180px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="资源能力" prop="resourceCapability">
            <el-input
              v-model="queryParams.resourceCapability"
              placeholder="请输入资源能力"
              clearable
              style="width: 180px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="联系人" prop="contactPerson">
            <el-input
              v-model="queryParams.contactPerson"
              placeholder="请输入联系人"
              clearable
              style="width: 180px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="资源类型">
            <el-select
              v-model="queryParams.resourceType"
              placeholder="请选择"
              clearable
              style="width: 220px"
            >
              <el-option label="大院大所" value="大院大所" />
              <el-option label="产业基金" value="产业基金" />
              <el-option label="服务机构" value="服务机构" />
              <el-option label="协会/校友会" value="协会/校友会" />
              <el-option label="重点企业" value="重点企业" />
              <el-option label="政府资源" value="政府资源" />
              <el-option label="其他资源" value="其他资源" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              <el-button type="success" icon="Plus" @click="openAddQuery">新增</el-button>
              <el-button type="success" icon="Upload" @click="handleExport">导出</el-button>
          </el-form-item>
        </template>
      </el-form>
    </el-card>

    <!-- 统计结果显示区域 -->
    <el-card class="list-card" style="margin-top: 18px" v-if="activeTab === '2'">
      <div class="statistics-container">
        <div class="statistics-grid">
          <div class="statistics-table">
            <table>
              <thead>
                <tr>
                  <th>资源归属</th>
                  <th>资源数</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in departmentStats" :key="index">
                  <td>{{ item.department }}</td>
                  <td>{{ item.count }}</td>
                </tr>
              </tbody>
            </table>
          </div>
          <div class="statistics-table">
            <table>
              <thead>
                <tr>
                  <th>资源类型</th>
                  <th>资源数</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in typeStats" :key="index">
                  <td>{{ item.type }}</td>
                  <td>{{ item.count }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </el-card>
    <!-- 普通列表显示区域 -->
    <el-card class="list-card" style="margin-top: 18px" v-else>
      <el-table v-loading="loading" :data="resourcesList" style="width: 100%" border>
          <el-table-column label="序号" width="80">
              <template #default="{ $index }">
                  {{ ($index + 1) + (queryParams.pageNum - 1) * queryParams.pageSize }}
              </template>
          </el-table-column>
          <el-table-column prop="resourceLevel" label="级别" width="120" show-overflow-tooltip>
            <template #default="scope">
              <el-tag 
                :class="getResourceLevelTagClass(scope.row.resourceLevel)"
                disable-transitions
              >
                {{ scope.row.resourceLevel }}
              </el-tag>
            </template>
          </el-table-column>

        
        <el-table-column prop="resourceName" label="资源名称" min-width="200" />
        <el-table-column prop="resourceType" label="资源类型" min-width="120" >
        <template #default="scope">
              <el-tag 
                :class="getResourceTypeTagClass(scope.row.resourceType)"
                disable-transitions
              >
                {{ scope.row.resourceType }}
              </el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="region" label="区域" min-width="100" />
        <el-table-column prop="contactPerson" label="联系人" min-width="80" />
        <el-table-column
          prop="contactPersonPosition"
          label="联系人职务"
          min-width="110"
        />
        <el-table-column prop="resourceCapability" label="资源能力" min-width="100" />
        <el-table-column prop="department" label="部门" min-width="100" />
        <el-table-column
          prop="coordinator"
          label="我司对接人"
          min-width="80"
          width="100"
          show-overflow-tooltip
        />
        <el-table-column label="操作" min-width="80" fixed="right">
          <template #default="{ row }">

              <el-button type="primary" link @click="editResource(row.id)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
      <!-- 新增弹窗-->
      <el-dialog
              v-model="dialogVisible"
              :title="dialogTitle"
              width="600px"
              @close="resetForm"
      >
          <el-form
                  ref="addFormRef"
                  :model="addForm"
                  :rules="addFormRules"
                  label-width="120px"
                  class="dialog-form"
          >
              <!-- 添加部门（自动填充，不可编辑） -->
              <el-form-item label="添加部门" prop="department">
                  <el-input v-model="addForm.department" disabled />
              </el-form-item>

              <!-- 资源级别 -->
              <el-form-item label="资源级别" prop="resourceLevel">
                  <el-select v-model="addForm.resourceLevel" placeholder="请选择">
                      <el-option label="一级资源" value="一级资源" />
                      <el-option label="二级资源" value="二级资源" />
                      <el-option label="三级资源" value="三级资源" />
                  </el-select>
              </el-form-item>

              <!-- 资源类型 -->
              <el-form-item label="资源类型" prop="resourceType">
                  <el-select v-model="addForm.resourceType" placeholder="请选择">
                      <el-option label="大院大所" value="大院大所" />
                      <el-option label="产业基金" value="产业基金" />
                      <el-option label="服务机构" value="服务机构" />
                      <el-option label="协会/校友会" value="协会/校友会" />
                      <el-option label="重点企业" value="重点企业" />
                      <el-option label="政府资源" value="政府资源" />
                      <el-option label="其他资源" value="其他资源" />
                  </el-select>
              </el-form-item>

              <!-- 资源名称 -->
              <el-form-item label="资源名称" prop="resourceName">
                  <el-input v-model="addForm.resourceName" placeholder="请输入资源名称"/>
              </el-form-item>

              <!-- 资源所在城市 -->
              <el-form-item label="资源所在城市" prop="region">
                  <el-input v-model="addForm.region" placeholder="请输入城市"/>
              </el-form-item>

              <!-- 资源能力 -->
              <el-form-item label="资源能力" prop="resourceCapability">
                  <el-input v-model="addForm.resourceCapability" placeholder="请输入资源能力" />
              </el-form-item>

              <!-- 联系人 -->
              <el-form-item label="联系人" prop="contactPerson">
                  <el-input v-model="addForm.contactPerson" placeholder="请输入联系人" />
              </el-form-item>

              <!-- 联系人职务 -->
              <el-form-item label="联系人职务" prop="contactPersonPosition">
                  <el-input v-model="addForm.contactPersonPosition" placeholder="请输入职务" />
              </el-form-item>

              <!-- 合作诉求 -->
              <el-form-item label="合作诉求" prop="cooperationDemands">
                  <el-input v-model="addForm.cooperationDemands" placeholder="请输入合作诉求" />
              </el-form-item>

              <!-- 合作类型 -->
              <el-form-item label="合作类型" prop="cooperationType">
                  <el-input v-model="addForm.cooperationType" placeholder="请输入合作类型" />
              </el-form-item>

              <!-- 合作卡点 -->
              <el-form-item label="合作卡点" prop="collaborationPoints">
                  <el-input v-model="addForm.collaborationPoints" placeholder="请输入合作卡点" />
              </el-form-item>

              <!-- 合作进展 -->
              <el-form-item label="合作进展" prop="progressCooperation">
                  <el-input v-model="addForm.progressCooperation" placeholder="请输入合作进展" />
              </el-form-item>

              <!-- 对接项目 -->
              <el-form-item label="对接项目" prop="dockingProject">
                  <el-input v-model="addForm.dockingProject" placeholder="请输入对接项目" />
              </el-form-item>

              <!-- 我司对接人（自动填充） -->
              <el-form-item label="我司对接人" prop="coordinator">
                  <el-input v-model="addForm.coordinator" />
              </el-form-item>

              <!-- 备注 -->
              <el-form-item label="备注" prop="remark">
                  <el-input
                          v-model="addForm.remark"
                          type="textarea"
                          :rows="4"
                          placeholder="请输入备注"
                  />
              </el-form-item>
          </el-form>

          <template #footer>
    <span class="dialog-footer">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </span>
          </template>
      </el-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from 'element-plus';
// 导入文件下载工具
import { download } from "@/utils/request";
import {
    getAttractInvestmentList,
    addAttractInvestmentList,
    selectAttractInvestmentOne,
    updateAttractInvestmentOne,
    excelDownload,
} from "@/api/AttractInvestment/resources/index.js";
import useUserStore from "@/store/modules/user.js";
const { proxy } = getCurrentInstance();
const userStr = useUserStore();
const { username, nickname, gszt, deptId, deptName } = userStr;


function dateOnlyFormatter(row, column, cellValue) {
  if (!cellValue) return "";
  return String(cellValue).split(" ")[0].split("T")[0];
}

const loading = ref(false);
const total = ref(0);
const resourcesList = ref([]);
const activeTab = ref("0");


// 统计数据
const departmentStats = ref([
  { department: "公司全部", count: 1043 },
  { department: "深圳项目", count: 330 },
  { department: "其他", count: 121 },
  { department: "双创中心", count: 113 },
  { department: "投资拓展中心", count: 103 },
  { department: "联健元和", count: 70 },
  { department: "科技中心", count: 62 },
  { department: "江宁项目", count: 54 },
  { department: "秦淮项目", count: 46 },
  { department: "总裁办", count: 39 },
  { department: "黄埭项目", count: 32 },
  { department: "运营服务中心", count: 31 },
  { department: "新零售", count: 20 },
]);

const typeStats = ref([
  { type: "重点企业", count: 400 },
  { type: "政府资源", count: 209 },
  { type: "协会/校友会", count: 165 },
  { type: "大院大所", count: 95 },
  { type: "服务机构", count: 68 },
  { type: "其他资源", count: 59 },
  { type: "产业基金", count: 47 },
]);

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  region: "",
  resourceName: "",
  resourceCapability: "",
  contactPerson: "",
  resourceType: "",
  status: 0,
  // 资源统计专用字段
  statDate: "",
  statType: "",
  statDepartment: "",
});


const addFormRef = ref(null);

// 添加一个响应式变量来标识当前是新增还是编辑模式
const isEditMode = ref(false);

// 计算弹窗标题
const dialogTitle = computed(() => {
    return isEditMode.value ? '编辑资源' : '新增资源';
});
// 弹窗控制变量
const dialogVisible = ref(false);

// 表单数据
const addForm = reactive({
    id: "", // 新增时为空，编辑时有值
    department: "",
    resourceLevel: "",
    resourceType: "",
    resourceName: "",
    region: "",
    resourceCapability: "",
    contactPerson: "",
    contactPersonPosition: "",
    cooperationDemands: "", // 替换 cooperationRequest
    cooperationType: "",
    collaborationPoints: "", // 替换 cooperationBlock
    progressCooperation: "", // 替换 cooperationProgress
    dockingProject: "", // 替换 project
    coordinator: "",
    remark: "",
});

// 表单校验规则
const addFormRules = {
    department: [{ required: true, message: "请输入部门", trigger: "blur" }],
    resourceLevel: [{ required: true, message: "请选择资源级别", trigger: "change" }],
    resourceType: [{ required: true, message: "请选择资源类型", trigger: "change" }],
    resourceName: [{ required: true, message: "请输入资源名称", trigger: "blur" }],
    region: [{ required: true, message: "请输入资源所在城市", trigger: "blur" }],
    resourceCapability: [{ required: true, message: "请输入资源能力", trigger: "blur" }],
    coordinator: [{ required: true, message: "我司对接人不能为空", trigger: "blur" }],
};

// 打开新增弹窗
function openAddQuery() {
    isEditMode.value = false; // 设置为新增模式
    addForm.id = "";
    addForm.department = deptName || "";
    addForm.coordinator = nickname || username || "";

    dialogVisible.value = true;
}

// 重置表单
function resetForm() {
    for (const key in addForm) {
        if (key !== "department" && key !== "coordinator") {
            addForm[key] = "";
        }
    }
    addForm.id = "";
}

// 提交表单
function submitForm() {
    addFormRef.value.validate((valid) => {
        console.log("id",addForm.id);
        if (valid) {
            if (addForm.id) {
                // 编辑模式
                updateAttractInvestmentOne(addForm)
                    .then((res) => {
                        if (res.code === 200) {
                            ElMessage.success("修改成功");
                            dialogVisible.value = false;
                            resetForm();
                            getList(); // 刷新列表
                        } else {
                            ElMessage.error(res.msg || "修改失败");
                        }
                    })
                    .catch((error) => {
                        console.error("请求出错:", error);
                        ElMessage.error("网络错误，请重试");
                    });
            } else {
                // 新增模式
                addAttractInvestmentList(addForm)
                    .then((res) => {
                        if (res.code === 200) {
                            ElMessage.success("添加成功");
                            dialogVisible.value = false;
                            resetForm();
                            getList(); // 刷新列表
                        } else {
                            ElMessage.error(res.msg || "添加失败");
                        }
                    })
                    .catch((error) => {
                        console.error("请求出错:", error);
                        ElMessage.error("网络错误，请重试");
                    });
            }
        }
    });
}
// 编辑资源
function editResource(id) {
    // 调用接口获取数据
    selectAttractInvestmentOne(id)
        .then((res) => {
            if (res.code === 200) {
                const data = res.data;
                // 设置为编辑模式
                isEditMode.value = true;
                // 填充表单
                addForm.id = data.id;
                addForm.department = data.department || "";
                addForm.resourceLevel = data.resourceLevel || "";
                addForm.resourceType = data.resourceType || "";
                addForm.resourceName = data.resourceName || "";
                addForm.region = data.region || "";
                addForm.resourceCapability = data.resourceCapability || "";
                addForm.contactPerson = data.contactPerson || "";
                addForm.contactPersonPosition = data.contactPersonPosition || "";
                addForm.cooperationDemands = data.cooperationDemands || "";
                addForm.cooperationType = data.cooperationType || "";
                addForm.collaborationPoints = data.collaborationPoints || "";
                addForm.progressCooperation = data.progressCooperation || "";
                addForm.dockingProject = data.dockingProject || "";
                addForm.coordinator = data.coordinator || "";
                addForm.remark = data.remark || "";

                // 打开弹窗
                dialogVisible.value = true;
            } else {
                ElMessage.error("获取数据失败");
            }
        })
        .catch((error) => {
            console.error("请求出错:", error);
            ElMessage.error("网络错误，请重试");
        });
}

const router = useRouter();

function getList() {
  loading.value = true;
  console.log("queryParams", queryParams);

  getAttractInvestmentList(queryParams)
    .then((res) => {
      console.log("接口返回数据:", res);
      const result = res;
      if (result && result.code === 200) {
        let rows = [];
        if (Array.isArray(result.rows)) {
          rows = result.rows;
        } else if (
          result.rows &&
          typeof result.rows === "object" &&
          typeof result.rows.length === "number"
        ) {
          rows = Array.from(result.rows);
        }
        console.log("处理后的rows:", rows);
        resourcesList.value = rows;
        total.value = result.total || 0;
      } else {
        resourcesList.value = [];
        total.value = 0;
      }
    })
    .catch(() => {
      console.error("请求出错:", error);
      resourcesList.value = [];
      total.value = 0;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 导出功能函数
function handleExport() {
    // 创建导出参数（移除分页参数，因为导出通常需要全部数据）
    const exportParams = {
        ...queryParams,
        pageNum: undefined,
        pageSize: undefined
    };

    proxy.$modal.loading("正在导出数据，请稍候...");

    // 调用后端导出接口
    excelDownload(exportParams)
        .then((response) => {
            // 检查响应类型是否为 blob
            if (response instanceof Blob) {
                // 正常的文件流
                const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
                const fileName = `产业资源列表_${new Date().toISOString().slice(0, 10)}.xlsx`;
                const link = document.createElement('a');
                link.href = window.URL.createObjectURL(blob);
                link.download = fileName;
                link.style.display = 'none';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                window.URL.revokeObjectURL(link.href);

                proxy.$modal.closeLoading();
                ElMessage.success("导出成功");
            } else {
                // 可能是错误响应
                proxy.$modal.closeLoading();
                ElMessage.error("导出失败");
            }
        });
}
function handleTabChange(tab) {
  queryParams.status = Number(tab.paneName);
  queryParams.pageNum = 1;
  getList();
}



onMounted(() => {
  getList();
});

function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}

function resetQuery() {
  // 重置所有查询参数
  queryParams.region = "";
  queryParams.resourceName = "";
  queryParams.resourceCapability = "";
  queryParams.contactPerson = "";
  queryParams.resourceType = "";
  queryParams.pageNum = 1;
  getList();
}
// 在 script 中添加以下函数
const getResourceLevelTagClass = (type) => {
  switch (type) {
    case '一级资源':
      return 'custom-tag-primary';
    case '二级资源':
      return 'custom-tag-secondary';
    case '三级资源':
      return 'custom-tag-tertiary';
    default:
      return 'custom-tag-default';
  }
};
const getResourceTypeTagClass = (type) => {
  switch (type) {
    case '大院大所':
      return 'custom-tag-primary';
    case '产业基金':
      return 'custom-tag-secondary';
    case '服务机构':
      return 'custom-tag-tertiary';
    case '协会/校友会':
      return 'custom-tag-one';
    case '重点企业':
      return 'custom-tag-two';
    case '政府资源':
      return 'custom-tag-three';
    default:
      return 'custom-tag-four';
  }
};
</script>

<style scoped>
/* 替换原来的 .custom-tag-* 样式为以下内容 */
.custom-tag-one {
  background-color: #f0fff4 !important;
  border-color: #9ae6b4 !important;
  color: #41999f !important;
}

.custom-tag-two {
  background-color: #ebf8ff !important;
  border-color: #90cdf4 !important;
  color: #5c3772 !important;
}

.custom-tag-three {
  background-color: #fff5f5 !important;
  border-color: #fed7d7 !important;
  color: #406484 !important;
}

.custom-tag-four {
  background-color: #f7fafc !important;
  border-color: #e2e8f0 !important;
  color: #cbaf58 !important;
}

.custom-tag-secondary {
  background-color: #f0fff4 !important;
  border-color: #9ae6b4 !important;
  color: #38a169 !important;
}

.custom-tag-tertiary {
  background-color: #ebf8ff !important;
  border-color: #90cdf4 !important;
  color: #3182ce !important;
}

.custom-tag-default {
  background-color: #f7fafc !important;
  border-color: #e2e8f0 !important;
  color: #4a5568 !important;
}
.resources-container {
  padding: 24px 32px 0 32px;
  min-height: 100vh;
}

.filter-card {
  margin-bottom: 12px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  border: 1px solid #f0f0f0;
}

.filter-form {
  padding: 8px 0 0 0;
}

.list-card {
  margin-bottom: 18px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  border: 1px solid #f0f0f0;
}

.el-table {
  border-radius: 8px;
  font-size: 15px;
}

.el-table th {
  color: #333;
  font-weight: 600;
  border-bottom: 1px solid #ebeef5;
}

.el-table td {
  color: #444;
  border-bottom: 1px solid #f0f0f0;
}

.el-button[type="primary"] {
  background: linear-gradient(90deg, #4f8cff 0%, #38c8fa 100%);
  border: none;
  color: #fff;
  border-radius: 6px;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(32, 159, 240, 0.08);
  transition: background 0.2s;
}

.el-button[type="primary"]:hover {
  background: linear-gradient(90deg, #2563eb 0%, #38c8fa 100%);
}

.el-dialog {
  border-radius: 10px;
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.15);
}

.el-dialog__header {
  border-radius: 10px 10px 0 0;
  font-size: 18px;
  font-weight: 600;
  color: #2563eb;
}

.el-dialog__body {
  padding: 28px 36px 18px 36px;
  min-height: 180px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.dialog-form {
  margin-top: 0;
}

.el-form-item {
  margin-bottom: 18px;
}

.el-form-item .el-link {
  font-size: 15px;
}

.el-form-item .el-upload {
  margin-top: 0;
}

.el-dialog__footer {
  border-radius: 0 0 10px 10px;
  padding: 12px 32px;
}

.el-upload {
  margin-top: 12px;
}

.el-link {
  font-size: 15px;
}

.el-alert {
  margin-bottom: 8px;
}

/* 统计图表样式 */
.statistics-container {
  display: flex;
  gap: 20px;
  padding: 20px;
}

.statistics-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.statistics-table {
  border: 1px solid #ddd;
  border-radius: 8px;
  overflow: hidden;
}

.statistics-table table {
  width: 100%;
  border-collapse: collapse;
}

.statistics-table th {
  background-color: #999;
  color: white;
  padding: 10px;
  text-align: left;
}

.statistics-table td {
  padding: 10px;
  border-bottom: 1px solid #eee;
}

.statistics-table tr:last-child td {
  border-bottom: none;
}
</style>
